﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using Convert.DataAccess;
using Convert.LOTSmodel;
using Convert.CPIAMmodel;
using System.Configuration;
using System.Data.OleDb;
using System.Windows;
namespace Convert.DBconverter
{
    class ProductGroupConverter
    {
        private static int BATCH_SAVE_SIZE = 5000;
        public static string LotsConnectionString; //= @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\LOTS\lots.mdb";//@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\LOTS\lots.mdb";//ConfigurationManager.ConnectionStrings["LOTStoCPIAMconvert.Properties.Settings.lotsConnectionString"].ConnectionString;
        public static string CpiamConnectionString; //= ConfigurationManager.ConnectionStrings["LOTStoCPIAMconvert.Properties.Settings.CPIAMPOSMaxRetailConnectionString"].ConnectionString;
        private static Dictionary<int, int> LotsReallocatedDepartmentDictionary;
        private static List<int> CPIAMDepartmentNumbers;
        public static Dictionary<int, int> ConvertProductGroup(string lotsConnectionString, string cpiamConnectionString)
        {
            LotsConnectionString = lotsConnectionString;
            CpiamConnectionString = cpiamConnectionString;
            CPIAMDepartmentNumbers = GetCurrentDepartmentNumbers(CpiamConnectionString);
            LotsReallocatedDepartmentDictionary = new Dictionary<int, int>();
            AllocatedDepartmentNos = new HashSet<int>();
            DataTable DeptFileDT = DataTables.CreateDeptFileDT();
            OleDbConnection dbConn = new OleDbConnection(LotsConnectionString);
            try
            {
                dbConn.Open();
                using (OleDbCommand command = dbConn.CreateCommand())
                {
                    command.CommandText = string.Format(@"SELECT ProductGroupID, ProductGroupName, DepartmentID FROM ProductGroup");
                    OleDbDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        ProductGroup productGroup = new ProductGroup();
                        int i = 0;
                        productGroup.ProductGroupID = reader.GetInt32(i);
                        productGroup.ProductGroupName = reader.IsDBNull(++i) ? null : reader.GetString(i);
                        productGroup.DepartmentID = reader.GetInt32(++i);
                        SaveDeptFile(productGroup, DeptFileDT);

                        if (DeptFileDT.Rows.Count % BATCH_SAVE_SIZE == 0)
                        {
                            SaveAllDataTables(CpiamConnectionString, DeptFileDT);
                        }
                    }
                    SaveAllDataTables(CpiamConnectionString, DeptFileDT);
                }
            }
            catch (Exception ex)
            {
                Logger.LogWarningAndError("Error in Convert productGroup ", ex);
                MessageBox.Show("Error converting productGroup: " + ex.Message + "\n\nStackTrace=" + ex.StackTrace);
            }
            finally
            {
                dbConn.Close();
            }
            return LotsReallocatedDepartmentDictionary;
        }

        private static void SaveAllDataTables(String ConnectionString, DataTable DeptFileDT)
        {
            if (DeptFileDT.Rows.Count > 0)
                dbSaveBatch.SaveBatch(DeptFileDT, "DeptFile", ConnectionString);
        }

        private static HashSet<int> AllocatedDepartmentNos;
        private static void SaveDeptFile(ProductGroup productGroup, DataTable DeptFileDT)
        {
            /*
            Guid deptID = Guid.NewGuid();
            string deptName = String.IsNullOrEmpty(productGroup.ProductGroupName) ? String.Empty : productGroup.ProductGroupName.Trim().ToUpper();
            int deptNo = productGroup.DepartmentID;
            int oldDeptNo = deptNo;
            deptNo = GetNextDepartmentNumber();
            */
            DeptFile deptFile = new DeptFile(productGroup.ProductGroupID, productGroup.ProductGroupName, 50.0m, productGroup.DepartmentID);
            DeptFile.SaveDeptFileToDataTable(deptFile, DeptFileDT);
            /*
            LotsReallocatedDepartmentDictionary[oldDeptNo] = deptNo;
            AllocatedDepartmentNos.Add(deptNo);
             */
            //DeptFileDT.Rows.Add(deptFile.DeptID, deptFile.DeptNo, deptFile.DeptName, deptFile.DeptMp, deptFile.DeptNoGroup);
        }


        private static List<int> GetCurrentDepartmentNumbers(String connectionString)
        {
            List<int> deptNos = new List<int>();

            String query = @"select deptNo from DeptFile";
            SqlConnection conn = null;
            SqlDataReader reader = null;

                conn = new SqlConnection(connectionString);
                conn.Open();

                SqlCommand command = new SqlCommand(query, conn);
                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    deptNos.Add(reader.GetInt32(0));
                }

                if (reader != null)
                    reader.Close();

                if (conn != null)
                    conn.Close();

            return deptNos;
        }

        private static int? nextDeptNumber;
        private static int GetNextDepartmentNumber()
        {
            if (!nextDeptNumber.HasValue)
            {
                nextDeptNumber = CPIAMDepartmentNumbers.Count==0? 0 : CPIAMDepartmentNumbers.Max();
            }

            nextDeptNumber = nextDeptNumber + 1;

            if (nextDeptNumber == 9999)
                nextDeptNumber++;

            return nextDeptNumber.Value;
        }

    }
}
